#include "vgdb.h"

int vim_connect()
{    
    char   *hostname   =   "localhost";
    //char   *password   =   "changeme";
    int     port       =   3219;

    int     listen_socket;
    int     accept_socket;
    //int     opt;

    struct sockaddr_in  socket_addr;
    struct hostent     *host;
    socklen_t           socket_len;

    if ((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        DEBUG_MESSAGE("socket() failed: %s\n",strerror(errno));
        return -1;
    }

    memset((void *)&socket_addr, 0, sizeof(socket_addr));
    socket_addr.sin_family = AF_INET;
    socket_addr.sin_port = htons(port);
    if ((host = gethostbyname(hostname)) == NULL) {
        close(listen_socket);
        DEBUG_MESSAGE("gethostbyname() failed: %s\n",strerror(errno));
        return -2;
    }
    memcpy((void *)&socket_addr.sin_addr, host->h_addr, (size_t)host->h_length);

    //opt = 1;
    //setsockopt(listen_socket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

    if (bind(listen_socket, (struct sockaddr *)&socket_addr, sizeof(socket_addr)) == -1) {
        close(listen_socket);
        DEBUG_MESSAGE("bind() failed: %s\n",strerror(errno));
        return -3;
    }

    if (listen(listen_socket, 5) == -1 ) {
        close( listen_socket );
        DEBUG_MESSAGE("listen() failed: %s\n",strerror(errno));
        return -4;
    }

    socket_len = (socklen_t)sizeof(socket_addr);

    if ((accept_socket = accept(listen_socket, (struct sockaddr *)&socket_addr, &socket_len)) == -1) {
        close(listen_socket);
        DEBUG_MESSAGE("accept() failed: %s\n",strerror(errno));
        return -5;
    }
    close(listen_socket);
    vim()->datsock = accept_socket;
    DEBUG_MESSAGE("connect to vim sucessfully\n");
    return 0;
}


void vim_init()
{
    vim()->pid     = -1;
    vim()->datsock = -1;
    vim()->blen    = VGDB_VMSG_BLEN;
    vim()->bnr     = VGDB_VMSG_BNR;
    vim()->state   = VGDB_VS_DETACHED;
    vim()->bcur    = 0;
    vim()->seqno   = 1;
    vim()->curofs  = 0;
    vim()->curln   = 0;
    vmsg_init();
}
